package com.library.servlet;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import java.io.IOException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Properties;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.library.dao.BookItem;
import com.library.dao.BookItemDAO;
import com.library.dao.BookTitle;
import com.library.dao.BookTitleDAO;
import com.library.dao.DAOFactory;
import com.library.dao.Lending;
import com.library.dao.LendingDAO;
import com.library.dao.MySQLDAOFactory;
import com.library.dao.Reservation;
import com.library.dao.ReservationDAO;
import com.library.dao.User;
import com.library.dao.UserDAO;

/**
 * Servlet implementation class ReturningServlet
 */
@WebServlet("/ReturningServlet")
public class ReturningServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ReturningServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		int userid = Integer.parseInt(request.getParameter("userid"));
		int bookid = Integer.parseInt(request.getParameter("bookid"));
		DAOFactory factory = new MySQLDAOFactory();
		UserDAO userDAO = factory.getUserDAO();
		User user = userDAO.findUser(userid);
		if (user != null) {
			BookItemDAO bookItemDAO = factory.getBookItemDAO();
			BookItem book = bookItemDAO.findByKey(bookid);
			if (book != null) {
				LendingDAO lendingDAO = factory.getLendingDAO();
				ArrayList<Lending> lendings = lendingDAO.getUserLending(userid, Resource.CONTINUOUS);
				Boolean borrowed = false;
				Lending lending = null;
				for (Lending i : lendings) {
					if (i.getBookitemId() == bookid) {
						borrowed = true;
						lending = i;
						break;
					}
				}
				if (borrowed) {
					acceptReturn(request, response, lending);
				}
				else {
					showError(Resource.ERROR_NOT_BORROWED, request, response);
				}
				
			} else {
				showError(Resource.ERROR_WRONG_BOOK_ID, request, response);
			}
		} else {
			showError(Resource.ERROR_WRONG_USER_ID, request, response);
		}
	}

	private void acceptReturn(HttpServletRequest request,
			HttpServletResponse response, Lending lending)
			throws ServletException, IOException {
		
		DAOFactory factory = new MySQLDAOFactory();
		LendingDAO lendingDAO = factory.getLendingDAO();
		
		// dat lending ve returned
		lending.setStatus(Resource.RETURNED);
		lendingDAO.updateLending(lending);
		
		// lay danh sach dat sach
		BookItemDAO bookItemDAO = factory.getBookItemDAO();
		BookItem bookitem = bookItemDAO.findByKey(lending.getBookitemId());
		ReservationDAO reservationDAO = factory.getReverationDAO();
		ArrayList<Reservation> reservations = reservationDAO.findByBookTitleId(bookitem.getBookTitleId(), Resource.WAITTING);
		
		if (reservations.size() == 0) { //Neu khong ai dat sach
			bookitem.setStatus(Resource.AVAILABLE);
			bookItemDAO.update(bookitem);
		} else {
			bookitem.setStatus(Resource.RESERVED);
			bookItemDAO.update(bookitem);
			Reservation resv = reservations.get(0);
			UserDAO userDAO = factory.getUserDAO();
			final User user = userDAO.findUser(resv.getUserId());
			
			BookTitleDAO bookTitleDAO = factory.getBookTitleDAO();
			final BookTitle booktitle = bookTitleDAO.findByKey(bookitem.getBookTitleId());
			
			new Thread()
	        {
	            public void run() {

	    			sendEmail(user, booktitle);
	            }
	        }.start();
			
			resv.setBookAvailableDate(new Date(Calendar.getInstance().getTimeInMillis()));
			resv.setStatus(Resource.PENDING);
			resv.setDate(new Date(Calendar.getInstance().getTimeInMillis()));
			reservationDAO.update(resv);
		}
		
		request.setAttribute("msg", "Trả sách thành công");
		request.setAttribute("lastpage", "librarian/returning.jsp");
		String add = "librarian/librariansuccesspage.jsp";
		RequestDispatcher dispatcher = request.getRequestDispatcher(add);
		dispatcher.forward(request, response);
	}

	private void sendEmail(User user, BookTitle booktitle) {
		Properties props = new Properties();
		props.put("mail.smtp.host", "mail.gmx.com");
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.starttls.enable", "true");
		props.put("mail.smtp.port", "587");
 
		Session session = Session.getDefaultInstance(props,
			new javax.mail.Authenticator() {
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication("bklibrary@gmx.com","aAaaa@12");
				}
			});
 
		try {
 
			Message message = new MimeMessage(session);
			message.setHeader("Content-Type", "text/plain; charset=UTF-8");
			message.setFrom(new InternetAddress("bklibrary@gmx.com"));
			message.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse(user.getEmail()));
			message.setSubject("Notification");
			message.setText("Dear " +user.getName() + "," +
					"\n\n Come and grab " + booktitle.getTitle());
 
			Transport.send(message);
 
			System.out.println("Done");
 
		} catch (MessagingException e) {
			throw new RuntimeException(e);
		}
		
	}
	


	private void showError(String errorMsg, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setAttribute("error", errorMsg);
		String add = "librarian/librarianerrorpage.jsp";
		request.setAttribute("lastpage", "librarian/returning.jsp");
		RequestDispatcher dispatcher = request.getRequestDispatcher(add);
		dispatcher.forward(request, response);
	}

}
